#include "colorbuttonpage.h"
#include <QPalette>
#include <QMessageBox>
#include <QRandomGenerator>

ColorButtonPage::ColorButtonPage(QWidget *parent) : QWidget(parent)
{
    // 初始化颜色调色板
    colorPalette = {
        QColor(Qt::red),
        QColor(Qt::green),
        QColor(Qt::blue),
        QColor(Qt::yellow),
        QColor(Qt::magenta),
        QColor(Qt::cyan)
    };

    // 创建主布局
    mainLayout = new QGridLayout(this);

    // 创建颜色选择按钮区域
    createColorButtons();

    // 创建控制面板布局（包含返回按钮和步数显示）
    QHBoxLayout *controlLayout = new QHBoxLayout();

    // 添加返回按钮
    QPushButton *backButton = new QPushButton("返回主菜单", this);
    connect(backButton, &QPushButton::clicked, this, &ColorButtonPage::returnToMain);
    controlLayout->addWidget(backButton);

    // 添加伸缩空间
    controlLayout->addStretch();

    // 添加步数显示标签
    stepLabel = new QLabel("步数: 0", this);
    stepLabel->setAlignment(Qt::AlignCenter);
    stepLabel->setStyleSheet("font-size: 16px; font-weight: bold;");
    controlLayout->addWidget(stepLabel);

    // 将控制面板添加到主布局
    mainLayout->addLayout(controlLayout, 1, 0, 1, colorPalette.size());

    // 创建游戏网格
    createGameGrid();

    // 初始化步数
    stepCount = 0;
}

void ColorButtonPage::createColorButtons()
{
    for (int i = 0; i < colorPalette.size(); ++i) {
        QPushButton *colorButton = new QPushButton(this);
        colorButton->setFixedSize(50, 50);

        // 设置按钮颜色
        QPalette pal = colorButton->palette();
        pal.setColor(QPalette::Button, colorPalette[i]);
        colorButton->setAutoFillBackground(true);
        colorButton->setPalette(pal);
        colorButton->update();

        // 连接点击信号
        connect(colorButton, &QPushButton::clicked, this, &ColorButtonPage::onColorButtonClicked);

        // 添加到布局
        mainLayout->addWidget(colorButton, 0, i);
    }
}

void ColorButtonPage::createGameGrid()
{
    gameGridLayout = new QGridLayout();
    gameGridLayout->setHorizontalSpacing(0);
    gameGridLayout->setVerticalSpacing(0);
    gameGridLayout->setContentsMargins(0,0,0,0);
    mainLayout->addLayout(gameGridLayout, 2, 0, 1, colorPalette.size());

    gameGrid.resize(gridSize);
    for (int row = 0; row < gridSize; ++row) {
        gameGrid[row].resize(gridSize);
        for (int col = 0; col < gridSize; ++col) {
            QPushButton *button = new QPushButton(this);
            button->setFixedSize(78, 80);

            // 随机选择初始颜色
            int colorIndex = QRandomGenerator::global()->bounded(colorPalette.size());
            QColor color = colorPalette[colorIndex];

            // 设置按钮颜色
            QPalette pal = button->palette();
            pal.setColor(QPalette::Button, color);
            button->setAutoFillBackground(true);
            button->setPalette(pal);
            button->update();

            // 连接点击信号
            connect(button, &QPushButton::clicked, this, &ColorButtonPage::onGridButtonClicked);

            // 添加到网格
            gameGrid[row][col] = button;
            gameGridLayout->addWidget(button, row, col);
        }
    }
}

void ColorButtonPage::onColorButtonClicked()
{
    // 获取被点击的颜色按钮
    selectedColorButton = qobject_cast<QPushButton*>(sender());
}

void ColorButtonPage::onGridButtonClicked()
{
    if (!selectedColorButton) {
        QMessageBox::information(this, "提示", "请先选择一种颜色");
        return;
    }

    QPushButton* clickedButton = qobject_cast<QPushButton*>(sender());

    // 找到按钮在网格中的位置
    int targetRow = -1, targetCol = -1;
    for (int row = 0; row < gridSize; ++row) {
        for (int col = 0; col < gridSize; ++col) {
            if (gameGrid[row][col] == clickedButton) {
                targetRow = row;
                targetCol = col;
                break;
            }
        }
        if (targetRow != -1) break;
    }

    if (targetRow == -1 || targetCol == -1) return;

    // 获取新旧颜色
    QColor newColor = selectedColorButton->palette().color(QPalette::Button);
    QColor originalColor = clickedButton->palette().color(QPalette::Button);

    // 如果颜色相同则不做任何操作
    if (newColor == originalColor) return;

    // 增加步数
    stepCount++;
    updateStepDisplay();

    // 颜色0填充
    floodFill(targetRow, targetCol, originalColor, newColor);

    // 检查是否获胜
    checkWinCondition();
}

void ColorButtonPage::updateStepDisplay()
{
    stepLabel->setText(QString("步数: %1").arg(stepCount));
}

void ColorButtonPage::floodFill(int row, int col, QColor originalColor, QColor newColor)
{
    if (!isValidPosition(row, col)) return;

    QPushButton *button = gameGrid[row][col];
    QColor currentColor = button->palette().color(QPalette::Button);

    if (currentColor != originalColor) return;

    // 设置新颜色
    QPalette pal = button->palette();
    pal.setColor(QPalette::Button, newColor);
    button->setPalette(pal);
    button->update();

    // 递归处理相邻按钮
    floodFill(row + 1, col, originalColor, newColor); // 下
    floodFill(row - 1, col, originalColor, newColor); // 上
    floodFill(row, col + 1, originalColor, newColor); // 右
    floodFill(row, col - 1, originalColor, newColor); // 左
}

bool ColorButtonPage::isValidPosition(int row, int col)
{
    return row >= 0 && row < gridSize && col >= 0 && col < gridSize;
}

void ColorButtonPage::checkWinCondition()
{
    QColor firstColor = gameGrid[0][0]->palette().color(QPalette::Button);
    bool allSame = true;

    for (int row = 0; row < gridSize && allSame; ++row) {
        for (int col = 0; col < gridSize && allSame; ++col) {
            QColor currentColor = gameGrid[row][col]->palette().color(QPalette::Button);
            if (currentColor != firstColor) {
                allSame = false;
            }
        }
    }

    if (allSame) {
        QMessageBox msgBox;
        msgBox.setWindowTitle("恭喜");
        msgBox.setText(QString("你赢了！\n所有按钮颜色相同！\n总步数: %1").arg(stepCount));
        msgBox.setStandardButtons(QMessageBox::Ok);
        msgBox.setDefaultButton(QMessageBox::Ok);

        // 显示消息框并等待用户点击
        int ret = msgBox.exec();

        // 点击OK还是关闭窗口，都返回主页面
        if (ret == QMessageBox::Ok || ret == QMessageBox::Close) {
            returnToMain();
        }
    }
}

void ColorButtonPage::resetGame()
{
    // 重置步数
    stepCount= 0;
    updateStepDisplay();

    // 清除旧网格
    QLayoutItem*child;
    while ((child = gameGridLayout->takeAt(0))) {
        if (child->widget()) {
            delete child->widget();
        }
        delete child;
    }

    // 创建新网格
    createGameGrid();

    // 重置选中的颜色按钮
    selectedColorButton= nullptr;
}

void ColorButtonPage::returnToMain()
{
    emit returnToMain();
    this->hide();
}
